package com.max.mil.fuwu.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import com.max.mil.common.util.DataPage;
import com.max.mil.fuwu.model.vo.Prod;
import com.max.mil.fuwu.model.yhd.Product;
import com.max.mil.fuwu.openapi.yhd.PromotionApi;
import com.max.mil.fuwu.service.ProdService;

public class ProdServiceImpl implements ProdService
{

	PromotionApi promotionApi = new PromotionApi();
	
	public static boolean isTrue(int mask, int position)
	{
		return (mask >> position & 0x1) == 1;
	}
	
	@Override
	public DataPage<Prod> getProdList(String ids, String codes, String name,
			String cateId, int mask, int pageNo, int pageSize) throws Exception
	{
		List<Prod> prodList = new ArrayList<Prod>();
		List<Product> productList = new ArrayList<Product>();
		
		//普通产品
		if(isTrue(mask,2))
		{
			int pageNoTmp = 1,totalPage=1;
			while(pageNoTmp++<=totalPage)
			{
				DataPage<Product> dpGenera = promotionApi.getProduct(0, name, ids, codes, null, null, isTrue(mask,0)?1:0, isTrue(mask,1)?1:0, pageNoTmp, 100);
				if(dpGenera.getList() != null) productList.addAll(dpGenera.getList());
			}
		}
		
		//系列产品
		if(isTrue(mask,3))
		{
			int pageNoTmp = 1,totalPage=1;
			while(pageNoTmp++<=totalPage)
			{
				DataPage<Product> dpSerial = promotionApi.getProduct(1, name, ids, codes, null, null, isTrue(mask,0)?1:0, isTrue(mask,1)?1:0, pageNoTmp, 100);
				if(dpSerial.getList() != null) productList.addAll(dpSerial.getList());
			}
		}
		
		
		//合并产品
		for(Product product:productList)
		{
			Prod prod = new Prod();
			prod.setId(String.valueOf(product.getProductId()));
			prod.setCode(product.getProductCode());
			prod.setName(product.getProductCname());
			prod.setImg(product.getProdImg());
			prod.setPrice(new Random().nextInt(1000));
			prod.setStock(new Random().nextInt(1000));
			prod.setUrl(product.getProdDetailUrl());
			if(product.getProdImg() != null)
			{
				for(String prodImg:product.getProdImg().split(","))
				{
					prod.setImg(prodImg.split("\\|")[1]);
					if(prodImg.split("\\|")[2].equals("1"))
						break;
				}
			}
			
			prodList.add(prod);
		}
		int totalCount = prodList.size();
		prodList = DataPage.subList(prodList, pageNo, pageSize);
		return new DataPage(prodList, pageNo, pageSize, totalCount);
	}
}
